import Vue from 'vue'
import Vuex from 'vuex'
import { heLotteryPanel, kouLotteryPanel, heAward, kouAward } from '@/common/award'
import {
  UPDATE_PAGE,
  UPDATE_USERINFO,
  UPDATE_USER_AWARD,
  UPDATE_PICK_WORKS,
  UPDATE_POSTER,
  UPDATE_HOTS,
  UPDATE_PRIZE,
  UPDATE_INIT_DATA,
  UPDATE_CURRENT_PAGE,
  UPDATE_LOTTERY_LIST
} from '@/store/mutation-types'
import { getAllPrizeList } from '@/common/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    pageName: 'loading',
    cname: '',
    currentPage: 0,
    my: {
      brand: -1,
      nickname: '',
      photo: '',
      content: ''
    },
    poster: '',
    hots: [],
    lotteries: [],
    prizeType: 0,
    isSaved: 0
  },
  getters: {
    lotteryPanel (state) {
      return state.my && state.my.brand === 0 ? heLotteryPanel : kouLotteryPanel
    },
    prize (state) {
      const awards = Object.values(state.my.brand === 0 ? heAward : kouAward)
      let award = null
      for (let i = 0; i < awards.length; i++) {
        console.log(awards[i].value, state.prizeType)
        if (awards[i].value === state.prizeType) {
          award = awards[i]
          break
        }
      }
      return award
    }
  },
  mutations: {
    // 切换页面
    [UPDATE_PAGE] (state, name) {
      state.pageName = name
    },
    [UPDATE_USERINFO] (state, cname) {
      state.cname = cname
    },
    [UPDATE_USER_AWARD] (state, index) {
      state.qid = index
    },
    [UPDATE_PICK_WORKS] (state, my) {
      state.my = my
    },
    [UPDATE_POSTER] (state, poster) {
      state.poster = poster
    },
    [UPDATE_HOTS] (state, hots) {
      state.hots = hots
    },
    [UPDATE_PRIZE] (state, index) {
      state.prizeType = index
    },
    [UPDATE_INIT_DATA] (state, data) {
      const { hot, my, prize, saved } = data
      state.hots = hot || []
      state.my = my || { brand: '', nickname: '', photo: '', content: '' }
      state.prizeType = prize && prize.type ? prize.type : 0
      state.isSaved = saved
    },
    [UPDATE_LOTTERY_LIST] (state, data) {
      console.log(data)
      state.lotteries = data || []
    }
  },
  actions: {
    [UPDATE_CURRENT_PAGE] (context, currentPage) {
      if (currentPage === 4 && !context.state.lotteries.length) {
        getAllPrizeList({ brand: context.state.my.brand }).then((result) => {
          const { status, data } = result
          context.commit(UPDATE_LOTTERY_LIST, status > 0 ? data : [])
        })
      }
    }
  },
  modules: {}
})
